import * as CONSTANT from '../utils/constant';
import _ from 'lodash';

class Socket {
    /**
     * @param {Object} url 连接的url地址
     */
    constructor() {
        this.url = '';
        // 是否连接成功
        this.is_connect = false;
        this.maxRetries = 10;
        this.queue = [];
        this.socket = null;
    }

    initSocket(url) {
        this.url = url;
        console.log('ws链接地址--->', url);
        console.log('开始连接');
        this.socketConnect();
    }

    /**
     * 连接socket
     */
    socketConnect() {
        if (this.socket || this.is_connect) return;
        console.log('准备连接socket', this.socket);
        this.socket = uni.connectSocket({
            url: this.url,
            header: { 'content-type': 'application/json' },
            complete: () => {}
        });
        console.log('准备连接socket', this.socket);
        this.socket.onOpen(() => {
            console.log('WebSocket连接已打开！');
            this.is_connect = true;
            this.sendCacheMessages();
            // 重置最大连接次数
            this.maxRetries = 10;
        });

        this.socket.onMessage(res => {
            const data = JSON.parse(res.data);
            if (data.type == 'state' && data.data.completed) {
                uni.$emit('complete');
            }
			if (data.type == 'state') {
				uni.$emit('FACE_STATE',data)
			}
        });

        this.socket.onClose(res => {
            console.warn('WebSocket 已关闭！', res);
			this.closeSocket()
        });

        this.socket.onError(error => {
            console.error('WebSocket连接打开失败，请检查！', error);
            this.throttledCloseSocket();
        });
    }

    /**
     * 发送缓存消息
     */
    async sendCacheMessages() {
        // 延迟1s执行
        await new Promise(resolve => setTimeout(resolve, 1000));
        if (_.isEmpty(this.queue)) return;
        if (!this.socket || !this.is_connect) return;
        console.log('发送缓存消息', this.queue);
        this.queue.forEach(data => {
            this.send(data);
        });
        console.log('发送缓存完毕');
        this.queue = [];
    }

    throttledCloseSocket = _.debounce(this.retrySocket, 1000, { leading: true, trailing: false });

    async closeSocket() {
        if (this.socket) this.socket.close();
        uni.closeSocket();
        this.socket = null;
        this.is_connect = false;
    }

    async retrySocket() {
        this.maxRetries--;
        if (this.maxRetries <= 0) {
            uni.showModal({
                title: '温馨提示',
                content: '网络连接异常，请检查网络情况',
                showCancel: false,
                confirmColor: '#E95505'
            });
            return;
        }
        await new Promise(resolve => setTimeout(resolve, 3 * 1000));
        if (this.socket) this.socket.close();
        uni.closeSocket();
        this.socket = null;
        this.is_connect = false;
        console.log('准备尝试重连socket---onError', this.socket);
        this.socketConnect(); // 重新连接socket
    }

    /**
     * 发送消息
     *
     * */
    send(data) {
        if (!this.socket || !this.is_connect) {
            this.queue.push(data);
            return;
        }
        try {
            // 字符串：直接发送文本帧
            if (typeof data === 'string') {
                this.socket.send({ data });
                return;
            }

            // 原始二进制：ArrayBuffer 直接发送
            if (data instanceof ArrayBuffer) {
                this.socket.send({ data });
                return;
            }

            // TypedArray：发送其底层 ArrayBuffer
            if (data && data.buffer instanceof ArrayBuffer) {
                this.socket.send({ data: data.buffer });
                return;
            }

            // 其他对象：按文本 JSON 发送（仅用于控制指令）
            this.socket.send({ data: JSON.stringify(data) });
        } catch (e) {
            console.error('WebSocket 发送失败：', e);
        }
    }
}

export default new Socket();
